require "option_parser"
require "http"

module Crylaem
  VERSION = "0.1.0"

  OptionParser.parse do |parser|
    parser.banner = "crylaem - host files and shorten links using laem.fun"
    parser.on "-v", "--version", "show version of program" do
      puts "#{VERSION}"
      exit
    end
    
    parser.on "-h", "--help", "show this" do
      puts parser
      exit
    end

    parser.on "-s LINK", "--shorten LINK", "shorten a link" do |unshortened|
      puts shorten(unshortened)
    end

    parser.on "-f FILE", "--filehost FILE", "host a file" do |fileloc|
      puts hostfile(fileloc)
    end
  end
end

def shorten(link)
  response = HTTP::Client.get "https://laem.fun/short?url=#{link}"
  if response.status_code == 200
    return response.body
  else
    raise "uh oh! got code #{response.status_code} in response."
  end
end

def hostfile(fileloc)
  IO.pipe do |reader, writer|
    channel = Channel(String).new(1)
  
    spawn do
      HTTP::FormData.build(writer) do |formdata|
        channel.send(formdata.content_type)

        fileName = File.basename(fileloc) + File.extname(fileloc)
        File.open(fileloc) do |fileio|
          metadata = HTTP::FormData::FileMetadata.new(filename: fileName)
          formdata.file("file", fileio, metadata)
        end
      end
  
      writer.close
    end
  
    headers = HTTP::Headers{"Content-Type" => channel.receive}
    response = HTTP::Client.post("https://laem.fun/upload", body: reader, headers: headers)
  
    if response.status_code == 200
      return response.body
    else
      raise "uh oh! got code #{response.status_code} in response."
    end
  end
end
